//
//  FishMapViewController.m
//  HelloWordPrimer
//
//  Created by Anton Johansson on 10/5/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FishMapViewController.h"
#import "CatchFlipInfoController.h"
#import "MapFlipsideVC.h"
#import "Catch.h"
#import "catchViewController.h"

@implementation FishMapViewController

@synthesize mapView;
@synthesize locationManager;
@synthesize managedObjectContext; // Get-Set managedObjectContext from appDelegate



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
    // Start the location manager.
    [[self locationManager] startUpdatingLocation];
	
	//debug purpose only
	if(managedObjectContext){
		NSLog(@"Exists");
	}
	else{
		NSLog(@"Doesn´t exist");
	}
	NSLog(@"did load");
	//dummy annotation	
	
	mapView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Catch" inManagedObjectContext:managedObjectContext];
	[request setEntity:entity];
	
	// Execute the fetch -- create a mutable copy of the result.
	NSError *error = nil;
	NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
	if (mutableFetchResults == nil) {
		// Handle the error.
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail		
	}
	
	for (Catch *c in mutableFetchResults) {
		NSLog([NSString stringWithFormat:@"%@,%@ long, lat", c.longitude, c.latitude]);
		CLLocationCoordinate2D cord;
		cord.latitude = [c.latitude doubleValue];
		cord.longitude = [c.longitude doubleValue];
		FishCatchAnnotation *catch = [[FishCatchAnnotation alloc] initWithCoordinate:cord];
		//hämta värden från c....
		catch.title = c.species;
		catch.subtitle = [[NSString alloc]initWithFormat:@"%@ Kg",c.weight];
		catch.sourceID = c.catchID;
		[mapView addAnnotation:catch];
	}
	[request release];
}
#pragma mark -
#pragma mark userActions

- (IBAction)zoomToUser {
	//One location is obtained.. zoom to that location
	CLLocation *location = [locationManager location];
	if (!location) {
		NSLog(@"Couldn't find location");
		return;
	}
	CLLocationCoordinate2D cord = location.coordinate;
	MKCoordinateRegion region;
	region.center=cord;
	//Set Zoom level using Span
	MKCoordinateSpan span;
	span.latitudeDelta=.005;
	span.longitudeDelta=.005;
	region.span=span;
	
	[mapView setRegion:region animated:TRUE];
}

-(void)showCatchInfo:(id)sender{
	NSLog(@"showCatch");
	int callerID = (int)[sender tag];
	
	NSLog([[NSString alloc]initWithFormat:@"Tag: %d",callerID]);
	
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Catch" inManagedObjectContext:managedObjectContext];
	[request setEntity:entity];
	
	// Execute the fetch -- create a mutable copy of the result.
	NSError *error = nil;
	NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
	if (mutableFetchResults == nil) {
		// Handle the error.
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail		
	}
	
	for (Catch *c in mutableFetchResults) {
		if([c.catchID intValue] == callerID){
			NSLog([[NSString alloc]initWithFormat:@"date: %@",c.catchDate]);
			NSLog([[NSString alloc]initWithFormat:@"species: %@",c.species]);
			NSLog([[NSString alloc]initWithFormat:@"weight: %@",c.weight]);
			
			NSLog([[NSString alloc]initWithFormat:@"photo: %@",c.photo]);
			
			CatchFlipInfoController *controller = [[CatchFlipInfoController alloc] initWithNibName:@"CatchFlipInfoView" bundle:nil];
			controller.delegate = self;
			controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
			[controller setTheCatch:c];
			[controller setCatchPhoto:c.photo];
	
			[self presentModalViewController:controller animated:YES];
			[controller release];
			
			break;
		}
	}
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
	//NSString *test = @"test";
	if(![annotation subtitle]){
		return nil;
	}
	
	FishCatchAnnotation *catchAnno = (FishCatchAnnotation *)annotation;
	
	NSLog([catchAnno title]);
	
	MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:catchAnno reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
	
    UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	
    advertButton.frame = CGRectMake(0, 0, 23, 23);
    advertButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    advertButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

	[advertButton addTarget:self action: @selector(showCatchInfo:) forControlEvents:UIControlEventTouchUpInside];
	advertButton.tag = [catchAnno sourceID].intValue;
	
	annView.rightCalloutAccessoryView = advertButton;
	annView.animatesDrop = YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}

- (IBAction)newCatch:(id)sender{
	// If it's not possible to get a location, then return.
	CLLocation *location = [locationManager location];
	if (!location) {
		NSLog(@"Couldn't find location");
		return;
	} 

	catchViewController *theController = [[catchViewController alloc]initWithNibName:@"catchViewController" bundle:nil];
	self.title = @"Cancel";
	[theController setNavController:[self navigationController]];
	[theController setManagedObjectContext:[self managedObjectContext]];
	[theController setLocation:[[self locationManager] location]];
	[theController setMapView:self.mapView];
	
	[[self navigationController] pushViewController:theController animated:YES];
	[theController release], theController = nil;
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}


#pragma mark -
#pragma mark FlipsideViewController

- (void)flipsideViewControllerDidFinish:(MapFlipsideVC *)controller {
	// TODO: get settings from controller
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showInfo {
	MapFlipsideVC *controller = [[MapFlipsideVC alloc] initWithNibName:@"MapFlipsideView" bundle:nil];
	controller.delegate = self;
	controller.mapView = self.mapView;
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}


# pragma mark -
# pragma mark Location manager

// Get or create location manager
- (CLLocationManager *)locationManager {
	
    if (locationManager != nil) {
        return locationManager;
    }
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.delegate = self;
	
    return locationManager;
}

// Location manager delagate calls this when new possition is found
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
  // Don't do nada
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
	return TRUE;
}



#pragma mark -
#pragma mark Memory management

- (void)viewDidUnload {
	mapView = nil;
	managedObjectContext = nil;
	locationManager = nil;
}

- (void)dealloc {
	[super dealloc];
	[mapView release];
	[managedObjectContext release];
	[locationManager release];  
}


@end
